﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data.Linq;

namespace XMM.Functions
{
    public class LanguageTools
    {
        /// <summary>
        /// Get the normalized Language-Abbreviation for the found language string.
        /// </summary>
        /// <param name="sAbbreviation">(string) Language-Abbreviation</param>
        /// <returns>(string) valid Abbreviation</returns>
        /// <remarks>e.g. Language-Code found by MediaInfo reads "GER" it will be transformed to "de-de" due to a replacementrule in abbreviations.xml. If the Language-Code has no replacement, it will be passed through as given in sAbbreviation.</remarks>
        public static string getNormalizedLanguage(string sAbbreviation)
        {
            if (System.IO.File.Exists(Tools.getInstallationPath() + "abbreviations.xml") == false)
                return sAbbreviation;

            try
            {
                XDocument xdAbbreviations = XDocument.Load(Tools.getInstallationPath() + "abbreviations.xml");

                var vAbbreviations = from replacements in xdAbbreviations.Descendants("abbreviations").Descendants("replacement") select replacements;

                if (vAbbreviations != null && vAbbreviations.Count() > 0)
                {
                    foreach (XElement xeReplacementRule in vAbbreviations)
                    {
                        XElement xeReplacementKey = (XElement)xeReplacementRule.Descendants("foundkey").First();

                        if (xeReplacementKey.Value == sAbbreviation)
                        {
                            XElement xeValidAbbreviation = (XElement)xeReplacementRule.Descendants("replace").First();
                            return xeValidAbbreviation.Value;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("Fehler beim Überprüfen des Sprachkürzels \"" + sAbbreviation + "\": " + ex.Message, "Fehler", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
            }

            return sAbbreviation;
        }

    }
}
